angular
.module('frontEnd')
.controller('listCtrl', function($scope,$location,$sce,getInforService,publicService) {
	$scope.isloadMoreAnswer = false;
	if($location.url().indexOf('lid') != -1) {
		$scope.inOldLesson = true;
		url = $location.url().split('?')[1];
		$scope.listType = $location.url().split('?')[0].split('/')[1];
		if(url.indexOf('ctype') == -1) {
			$scope.questionType = url.split('&')[0].split('=')[1];
			$scope.lid = url.split('&')[1].split('=')[1];
			$scope.ctype = 0;
		} else {
			$scope.questionType = url.split('&')[0].split('=')[1];
			$scope.lid = url.split('&')[1].split('=')[1];
			$scope.ctype = url.split('&')[2].split('=')[1];
		}
	} else {
		console.log('这是新课');
	}
	
	$scope._Lesson = {};
	$scope.questionPage = 0;
	getInforService.get('http://api.mengma.com/lesson/title',{lid: $scope.lid,ctype: $scope.ctype}).success(function(data) {
		if(data) {
			$scope._Lesson.title = data;
		}
	});
	$scope.isLogin = true;
	$scope.getAllQuestions = function(determineLoadMore, listType) {
		param = {
			lid: $scope.lid,
			ctype: $scope.ctype,
			type: $scope.questionType,
			page: $scope.questionPage,
		}
		if(listType == 'anslist') {
			$scope.anlistType = parseInt($scope.questionType) + 3;//type：4为练习题1，5为练习题2
			param.type = $scope.anlistType;
		}
		getInforService.get("http://api.mengma.com/questions/lesson_relative",param).success(function(data) {
			if(!($scope.questions)) {
				$scope.questions = [];
			}
			try {
				for(var i = 0; i < data.questions.length; i++) {
					data.questions[i].user.name = data.questions[i].user.name == "" ? ("萌小码_"+ data.questions[i].uid) : data.questions[i].user.name
					if(listType == 'anslist') {
						if(!$scope.inOldLesson) {
							content = $sce.trustAsHtml(data.questions[i].content);
							data.questions[i].content = [];
							data.questions[i].content[0] = {};
							data.questions[i].content[0].file_name = '主文件';
							data.questions[i].content[0].codes = content;
							for(var j = 0; j < data.questions[i].content.length; j++) {
								if(j == 0) {
									data.questions[i].content[j].class_name = 'active';
								} else {
									data.questions[i].content[j].class_name = '';
								}
							}
						} else {
							data.questions[i].content = $sce.trustAsHtml(data.questions[i].content);
							data.questions[i].class_name = "mm_anlist_content";
						}
						
					} else {
						data.questions[i].cogListShow = false;
						data.questions[i].answerShow = false;
						data.questions[i].content = data.questions[i].content.replace('/<a\s*href/g', '<a target="_blank" href>')
						data.questions[i].content = $sce.trustAsHtml(data.questions[i].content);
					}
					if(determineLoadMore) {
						$scope.questions.push(data.questions[i]);
					} else {
						$scope.questions = data.questions;
					}
				}
			}catch(e){
				console.log(e);
			}
			if(listType == "qlist") {
				$scope.quesLoadMore = data.loadmore;
				if($scope.questions.length == 0) {
					$("#questionShow").css('display','none');
					$("#sorry").css("display","block");
					$("#sorry").height($(".mm_lesson_ask").height() - 60);
				} else {
					$(".mm_question_wrap").css("background-image","linear-gradient(-180deg, #DDE5E7 0%, #EDE8E3 100%)");
					$("#questionShow").css('display','block');
					$("#sorry").css("display","none");
				}
			} else {
				$scope.isloadMoreAnswer = data.loadmore;
				$scope.answerLists = $scope.questions;
				console.log($scope.answerLists);
				$(".mm_lesson_ask").css("padding-bottom","0");
			}
		});
	}
	$scope.showQuestions = function() {
		if($scope.questions.length == 0) {
			$("#sorry").css("display","block");
		}
		$scope.AskedShow = false;
	}
	$scope.questionLoadMore = function() {
		$scope.questionPage = $scope.questionPage + 1;
		param.page = $scope.questionPage;
		$scope.getAllQuestions(true, $scope.listType);
	}
	$scope.loadMoreAnswer = function() {
		$scope.questionPage = $scope.questionPage + 1;
		param.page = $scope.questionPage;
		$scope.getAllQuestions(true, $scope.listType);
	}
	$scope.stopPropagation = function(e) { 
		if (e.stopPropagation) 
			e.stopPropagation(); 
		else 
			e.cancelBubble = true; 
	}
	$scope.scroll = function(selector) {
		if(!(navigator.userAgent.indexOf('Mac OS X') > 0)) {
			selector.niceScroll({
				styler:"fb", 
				cursorwidth:"8px",
				cursorcolor:"#7a7777",
				cursorborder:"",
				horizrailenabled: false,
				zindex:999
			});
		}
	}
	if($scope.inOldLesson) {
		if($scope.listType == 'qlist') {
			$scope.getAllQuestions(false, $scope.listType);
			$('.sorry').css('padding-top','20%');
		} else {
			$scope.getAllQuestions(false, $scope.listType);
		}
	}
})
.directive('qlistcard',function($location,getInforService,publicService){
	return {
		restrict:'E',
		replace:true,
		transclude:true,
		templateUrl:"http://s.mengma.com/public/qlist/qlistIndex.html",
		controller: function($scope) {
			if($location.url().indexOf('qlist') != -1 || $location.url().indexOf('anslist') != -1) {
				$('.mm_lesson_ask').css({bottom: 0});
			} else {
				$('.mm_lesson_ask').css({bottom: -($('.mm_lesson_ask').height()+100)});
			}
			$scope.scroll($('.mm_question_wrap'));
			$scope.scroll($('.toAskBox'));
			$scope.goToAsk = function() {
				$("#sorry").css("display","none");
				$scope.AskedShow = true;
				$scope.title = "";
				$scope.titleNum = $scope.title.length;
				$scope.questionPage = 0;
				$scope.titleCount = function() {
					$scope.titleNum = $scope.title.length;
				}
				$scope.titleNum = 0;
				toolbar = ['bold', 'italic', 'underline', '|', 'code', 'image', 'link', '|', 'ol', 'ul', 'blockquote', 'strikethrough','|', 'markdown'];
				editor = new Simditor({
					textarea: $("#editor"),
					placeholder: '请在这里输入问题描述（上传图片大小不能超过2M）',
					toolbar: toolbar,
					pasteImage: true,
					cleanPaste: true,
					upload: {
						url: 'http://api.mengma.com/questions/upload',
					},
				});
			}
			$scope.submit = function() {
				if($scope.titleNum < 10) {
					publicService.popupTip(false, "标题需要10~35个字符！");
					return;
				}
				content = $("#editor").val();
				if((encodeURIComponent(content).length > 60000)) {
					publicService.popupTip(false, "输入的内容超过长度限制");
					return;
				}
				tagContent = []
				tagContent[0] = $scope.tag1;
				tagContent[1] = $scope.tag2;
				tagContent[2] = $scope.tag3;
				param = {
					lid: $scope.lid,
					ctype: $scope.ctype,
					title: $scope.title,
					content: content,
					tags: tagContent,
					type: $scope.questionType
				}
				getInforService.operation('http://api.mengma.com/questions','POST',param).success(function(data) {
					function goHome() {
						$scope.AskedShow = false;
						$scope.getAllQuestions(false,$scope.listType);
						Phenix.hide();
					}
					if(data.code == 200002) {
						publicService.popupIntergal('提问成功','积分+10',goHome);
					} else {
						publicService.popupTip(false, data.msg);
					}
				});
			}
			$scope.showQuestions = function() {
				if($scope.questions.length == 0) {
					$("#sorry").css("display","block");
				}
				$scope.AskedShow = false;
			}
		}
	}
})
.directive('qlistmaincard', function(getInforService){
	return {
		restrict: 'E',
		transclude: true,
		templateUrl: "http://s.mengma.com/public/qlist/main.html",
		controller: function($scope){

		}
	}
})
.directive('questionscard',  function(getInforService, $sce, publicService){
	return {
		restrict: 'E',
		transclude: true,
		templateUrl: "http://s.mengma.com/public/qlist/question.html",
		controller: function($scope){
			$scope.likeQuestion = function(index) {
				if(!$scope.isLogin) {
					$("#login_tip").css("display","block");
				} else {
					aqid = $scope.questions[index].aqid;
					param = {
						aqid: aqid,
						fields: "like"
					}
					getInforService.operation('http://api.mengma.com/questions','PUT',param).success(function(data) {
						if(data.code == "0") {
							$scope.questions[index].liked = 1;
							$scope.questions[index].like_num = parseInt($scope.questions[index].like_num) + 1;
						} else {
							publicService.popupTip(false,data.msg);
						}
					});
				}
			}
			$scope.cogShow = function(event,index) {
				if(!$scope.isLogin) {
					$("#login_tip").css("display","block");
				} else {
					if(index == undefined) {
						question = $scope.question;
					} else {
						question = $scope.questions[index];
					}
					if(!question.cogListShow) {
						question.cogListShow = true;
					} else {
						question.cogListShow = false;
					}
				}
			}
			$scope.supplyQuestion = function(index) {
				if(index == undefined) {
					question = $scope.question;
				} else {
					question = $scope.questions[index];
				}
				question.supply = true;
				question.cogListShow = false;
			}
			$scope.submitSupply = function(index) {
				if(index == undefined) {
					question = $scope.question;
				} else {
					question = $scope.questions[index];
				};
				content = question.supplyContent;
				if(encodeURIComponent(content).length > 30000) {
					publicService.popupTip(false, "输入的内容超过长度限制");
					return;
				};
				if(content == "") {
					publicService.popupTip(false, "内容不能为空");
					return
				};
				param = {
					aqid: question.aqid,
					content: content
				};
				getInforService.operation('http://api.mengma.com/supplements','POST',param).success(function(data) {
					if(data.code == "0") {
						question.supplys.push(content);
						question.supply = false;
					}
				});
			}
			$scope.cancelSupply = function(index) {
				if(index == undefined) {
					question = $scope.question;
				} else {
					question = $scope.questions[index];
				}
				question.supply = false;
			}
			$scope.deleteQuestion = function(index) {
				if(index == undefined) {
					question = $scope.question;
				} else {
					question = $scope.questions[index];
				}
				param = {
					aqid: question.aqid,
					type: 2
				}
				console.log(param);
				getInforService.operation('http://api.mengma.com/questions','DELETE', param).success(function(data) {
					question.cogListShow = false;
					if(data.code == "200001") {
						publicService.popupTip(true, data.msg);
						param = {
							lid: $scope.lid,
							ctype: $scope.ctype,
							type: $scope.questionType,
							page: $scope.questionPage,
						}
						$scope.getAllQuestions(false,$scope.listType);
					} else {
						publicService.popupTip(false, data.msg);
					}
				});
			}
			$scope.reportQuestion = function(index) {
				if(index == undefined) {
					question = $scope.question;
				} else {
					question = $scope.questions[index];
				}
				param = {
					aqid: question.aqid,
					fields: "report"
				}
				getInforService.operation('http://api.mengma.com/questions','PUT',param).success(function(data) {
					if(data.code == 0) {
						publicService.popupTip(true, data.msg);
					} else {
						publicService.popupTip(false, data.msg);
					}
					question.cogListShow = false;
				});
			}
			$scope.getAnswers = function(param, determineLoadMore) {
				getInforService.get('http://api.mengma.com/answers',param).success(function(data) {
					$scope.answerShow = true;
					if(data) {
						if(data.t != null) {
							if(!($scope.answer_t)) {
								$scope.answer_t = '';
							}
							data.t[0].user.name = data.t[0].user.name == "" ? ("萌小码_"+ data.t[0].uid) : data.t[0].user.name;
							data.t[0].content = data.t[0].content.replace('/<a\s*href/g', '<a target="_blank" href>')
							data.t[0].content = data.t[0].content; //此处应该有trustHTML方法
							$scope.answer_t = data.t[0];
							$scope.answer_t.commented = false;
						}
						if(data.s != null) {
							if(!($scope.answer_s)) {
								$scope.answer_s = [];
							}
							$scope.answer_s = [];
							try {
								for(var i = 0; i < data.s.list.length; i++) {
									data.s.list[i].user.name = data.s.list[i].user.name == "" ? ("萌小码_"+ data.s.list[i].user.uid) : data.s.list[i].user.name
									data.s.list[i].content = data.s.list[i].content.replace('/<a\s*href/g', '<a target="_blank" href>')
									data.s.list[i].content = data.s.list[i].content;
									data.s.list[i].commented = false;
									if(determineLoadMore) {
										$scope.answer_s.push(data.s.list[i]);
									}
								}
							}catch(e){
								console.log(e);
							}
							if(!determineLoadMore) {
								$scope.answer_s = data.s.list;
							}
							console.log($scope.answer_s);
							$scope.answerLoadMoreShow = data.s.loadmore;
						}
					}
				});
			}
			$scope.toggleAnswer = function(index) {
				question = $scope.questions[index];
				if(question.answerShow) {
					question.answerShow = false;
					question.answered = false;
				} else {
					question.answerShow = true;
					for(var i = 0; i < $scope.questions.length; i++) {
						if(index != i) {
							$scope.questions[i].answerShow = false;
							$scope.questions[i].answered = false;
						}
					}
					param = {
						aqid: question.aqid
					}
					$scope.getAnswers(param,false);
				}
			}
		}
	};
})
.directive('answercard', function(getInforService,publicService){
	return {
		restrict: 'E',
		transclude: true,
		templateUrl: "http://s.mengma.com/public/qlist/answer.html",
		controller: function($scope){
			$scope.answerPage = 0;
			$scope.toAnswer = function(index) {
				if(!$scope.isLogin) {
					$("#login_tip").css("display","block");
				} else {
					question = $scope.questions[index];
					question.answered = true;
					toolbar = ['bold', 'italic', 'underline', '|', 'code', 'image', 'link', '|', 'ol', 'ul', 'blockquote', 'strikethrough','|', 'markdown'];
					editor = new Simditor({
						textarea: $(".editor"),
						placeholder: '请在这里输入问题描述（上传图片大小不能超过2M）',
						toolbar: toolbar,
						pasteImage: true,
						cleanPaste: true,
						upload: {
							url: 'http://api.mengma.com/questions/upload',
						},
					});
				}
			}
			$scope.submitAnswer = function(index) {
				question = $scope.questions[index];
				content = $(".editor").val();
				if(content.length == 0) {
					publicService.popupTip(false, "内容不能为空");
					return;
				}
				if(encodeURIComponent(content).length > 60000) {
					publicService.popupTip(false, "输入的内容超过长度限制");
					return;
				}
				if($(".simditor-body").find("img").length > 10) {
					publicService.popupTip(false, "上传的图片数量不能超过10张");
					return;
				}
				param = {
					aqid: question.aqid,
					content: content
				}

				getInforService.operation('http://api.mengma.com/answers','POST', param).success(function(data) {
					if(data.code == 0) {
						function refresh() {
							param = {
								lid: $scope.lid,
								ctype: $scope.ctype,
								type: $scope.questionType,
								page: $scope.questionPage,
							}
							$scope.getAllQuestions(false, $scope.listType);
							question.answerShow = false;
							question.answered = false;
							Phenix.hide();
						}
						publicService.popupIntergal("回答成功", '积分+5', refresh);
					} else {
						publicService.popupTip(false, data.msg);
					}
				});
			}
			$scope.likeAnswer = function(index, type) {
				if(!$scope.isLogin) {
					$("#login_tip").css("display","block");
				} else {
					if(type == 0) {
						aaid = $scope.answer_s[index].aaid;
					} else {
						aaid = $scope.answer_t.aaid;
					}
					param = {
						aaid: aaid,
						answer_type: type,
						fields: "like"
					}
					getInforService.operation('http://api.mengma.com/answers','PUT', param).success(function(data) {
						if(data.code == 0) {
							if(type == 1) {
								$scope.answer_t.like_num = parseInt($scope.answer_t.like_num) + 1;
								$scope.answer_t.liked = 1;
							} else {
								$scope.answer_s[index].like_num = parseInt($scope.answer_s[index].like_num) + 1;
								$scope.answer_s[index].liked = 1;
							}
						} else {
							publicService.popupTip(true,data.msg);
						}
					});
				}
			}
			$scope.getComments = function(param, determineLoadMore){
				getInforService.get('http://api.mengma.com/comments',param).success(function(data) {
					if(!($scope.comments)) {
						$scope.comments = [];
					}
					if(data.code == "400225") {
						$scope.comments = [];
					} else {
						if(data.aclist.length > 0) {
							for(var i = 0; i < data.aclist.length; i++) {
								data.aclist[i].user_infor.name = (data.aclist[i].user_infor.name == "") ? "萌小码_" + data.aclist[i].user_infor.uid : data.aclist[i].user_infor.name
								try {
									data.aclist[i].content = $sce.trustAsHtml(data.aclist[i].content);
								}catch(e){}
								if(determineLoadMore) {
									$scope.comments.push(data.aclist[i]);
								} else {
									$scope.comments = data.aclist;
								}
							}
						}
					}
					$scope.commentLoadMoreShow = data.loadmore;
				});
			}
			$scope.toggleComment = function(index, answerType) {
				if(!$scope.isLogin) {
					$("#login_tip").css("display","block");
				} else {
					$scope.answerType = answerType;
					if(answerType == 0) {
						if(!$scope.answer_s[index].commented) {
							$scope.answer_s[index].commented = true;
							param = {
								aaid: $scope.answer_s[index].aaid,
								answer_type: answerType
							}
							$scope.getComments(param, false);
						} else {
							$scope.answer_s[index].commented = false;
						}
					} else {
						if(!$scope.answer_t.commented) {
							$scope.answer_t.commented = true;
							param = {
								aaid: $scope.answer_t.aaid,
								answer_type: answerType
							}
							$scope.getComments(param, false);
						} else {
							$scope.answer_t.commented = false;
						}
					}
				}
			}
			$scope.answerLoadMore = function(index) {
				$scope.answerPage++;
				param = {
					aqid: $scope.questions[index].aqid,
					page: $scope.answerPage
				}
				$scope.getAnswers(param, true);
			}
		}
	};
})
.directive('commentcard', function(getInforService,publicService){
	return {
		restrict: 'E',
		transclude: true,
		templateUrl: "http://s.mengma.com/public/qlist/comment.html",
		controller: function($scope){
			$scope.submitComentContent = "";
			$scope.commentPage = 0;
			$scope.commentLoadMore = function(index) {
				$scope.commentPage++;
				if($scope.answerType == 0) {
					aaid: $scope.answer_s[index].aaid;
				} else {
					aaid: $scope.answer_t.aaid;
				}
				param = {
					aaid: aaid,
					answer_type: $scope.answerType,
					page: $scope.commentPage
				}
				$scope.getComments(param, true);
			}
			$scope.submitComment = function(index) {
				content = $scope.submitComentContent;
				if(content == "") {
					publicService.popupTip(false, "内容不能为空");
					return;
				}
				if(encodeURIComponent(content).length > 10000) {
					publicService.popupTip(false, "输入的内容超过长度限制");
					return;
				}
				if($scope.answerType == 0) {
					answer = $scope.answer_s[index];
				} else {
					answer = $scope.answer_t;
				}
				param = {
					aaid: answer.aaid,
					content: content,
					answer_type: $scope.answerType
				}
				getInforService.operation('http://api.mengma.com/comments','POST', param).success(function(data) {
					if(data.code == 0) {
						Param = {
							aaid: answer.aaid,
							answer_type: $scope.answerType
						}
						$scope.getComments(Param, false);
						$scope.submitComentContent = "";
						answer.comment_num = parseInt(answer.comment_num) + 1;
					} else {
						publicService.popupTip(false, data.msg);
					}
				});

			}
		}
	};
})
.directive('askcard', ['getInforService', function(getInforService){
	return {
		restrict: 'E',
		transclude: true,
		templateUrl: "http://s.mengma.com/public/qlist/ask.html",
		controller: function($scope){

		}
	}
}])
.directive('anslistcard',function($http,getInforService){
	return {
		restrict: 'E',
		transclude: true,
		templateUrl: "http://s.mengma.com/public/anslist/anslistIndex.html",
		controller: function($scope){
			if($scope.listType == 'anslist') {
				$('.mm_lesson_answer').css({bottom: 0});
			} else {
				$('.mm_lesson_answer').css({bottom: -($('.mm_lesson_answer').height()+100)});
			}
			$scope.scroll($('.mm_answer_wrap'));
		}
	}
})
.directive('ansmaincard',function(getInforService,publicService){
	return {
		restrict: 'E',
		transclude: true,
		templateUrl: "http://s.mengma.com/public/anslist/main.html",
		controller: function($scope){
			$scope.thumbUp = function(index) {
				if(!$scope.isLogin) {
					$("#login_tip").css("display","block");
				} else {
					aqid = $scope.answerLists[index].aqid;
					param = {
						aqid: aqid,
						answer_type: 2,
						fields: "like"
					}
					getInforService.operation('http://api.mengma.com/questions','PUT', param).success(function(data) {
						if(data.code == 0) {
							$scope.answerLists[index].like_num = parseInt($scope.answerLists[index].like_num) + 1;
							$scope.answerLists[index].liked = 1;
						} else {
							publicService.popupTip(false,data.msg);
						}
					});
				}
			};
		}
	}
})
.directive('anslistscard',function($http,getInforService){
	return {
		restrict: 'E',
		transclude: true,
		templateUrl: "http://s.mengma.com/public/anslist/answers.html",
		controller: function($scope){
		}
	}
})